package com.weng.cloud.starter.batch.config;

import com.weng.cloud.starter.batch.factory.CsvItemRdWrFactory;
import com.weng.cloud.starter.batch.validator.TestValidator;
import com.weng.cloud.starter.dataSource.config.SpringDataSourceAutoConfiguration;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: weng
 * @Date: 2022/3/19
 * @Description: com.weng.cloud.starter.batch.batch
 *
 * 我感觉在配置里面写死批处理流程不是很好...
 *  因此 监听器、校验器 并没有通过配置类注入到IOC
 */
//@Configuration
//@EnableBatchProcessing
//@Import(SpringDataSourceAutoConfiguration.class)
public class SpringBatchAutoConfiguration {

    /**
     * JobRepository定义：Job的注册容器以及和数据库打交道（事务管理等）
     * @param dataSource
     * @param transactionManager
     * @return
     * @throws Exception
     */
    @Bean(name = "testJobRepository")
    public JobRepository testJobRepository(DataSource dataSource, PlatformTransactionManager transactionManager) throws Exception{
        JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
        jobRepositoryFactoryBean.setDatabaseType("mysql");
        jobRepositoryFactoryBean.setTransactionManager(transactionManager);
        jobRepositoryFactoryBean.setDataSource(dataSource);
        return jobRepositoryFactoryBean.getObject();
    }

    /**
     * jobLauncher定义： job的启动器,绑定相关的jobRepository
     * @param testJobRepository
     * @return
     * @throws Exception
     */
    @Bean
    public SimpleJobLauncher testSimpleJobLauncher(@Qualifier("testJobRepository") JobRepository testJobRepository) {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        // 设置jobRepository
        jobLauncher.setJobRepository(testJobRepository);
        return jobLauncher;
    }

    /**
     * <br/>function: CSV文件的行处理(读/写)器对象的工厂
     * <br/>tip:
     *
     * @param: [dataSource]
     * @return: com.weng.cloud.starter.batch.factory.CsvItemRdWrFactory
     * @author: weng
     * @date: 2022/3/20 15:59
     */
    @Bean
    public CsvItemRdWrFactory csvItemRdWrFactory(DataSource dataSource){
        return new CsvItemRdWrFactory(dataSource);
    }

}
